import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { MessageBox } from 'element-ui'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/tokenLogin'] // no redirect whitelist
const whitePath = ['/view', '/joinDate']
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  hasUser = localStorage.getItem('userName')
  if (whitePath.indexOf(to.path) > -1) {
    next()
  } else if (hasUser) {
    if (hasOldUser != hasUser) {
      if (hasOldUser) {
        MessageBox({
          title: '提示',
          message: '检测到系统存在登录用户变更，请点击确定按钮刷新页面！',
          showClose: false,
          callback: () => {
            window.location.reload();
          }
        })
        return
      }
      hasOldUser = hasUser
    }
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      await store.dispatch('permission/generateRoutes')
      next()
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      await store.dispatch('tagsView/delAllViews', null, { root: true })
      next(`/login`)
      hasOldUser = ''
      hasUser = ''
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
